import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useModelerStore = defineStore('modeler', () => {
    const modeler = ref(null);
    const activeElement = ref(null);
    const activeElementType = ref('');
    const activeElementBusinessObject = ref(null);

    // 设置模型器实例
    function setModeler(instance) {
        modeler.value = instance;
    }

    // 设置当前选中的元素
    function setActiveElement(element) {
        activeElement.value = element;
        activeElementType.value = element?.type.split(':')[1] || '';
        activeElementBusinessObject.value = element?.businessObject;
    }

    // 更新元素属性
    function updateElementProperties(properties) {
        if (!modeler.value || !activeElement.value) return;

        const modeling = modeler.value.get('modeling');
        modeling.updateProperties(activeElement.value, properties);
    }

    // 创建Flowable扩展属性
    function createFlowableExtension(element, properties) {
        const moddle = modeler.value.get('moddle');
        const modeling = modeler.value.get('modeling');

        // 创建Flowable扩展对象
        const extensionElements = moddle.create('bpmn:ExtensionElements', {
            values: [
                moddle.create('flowable:Properties', {
                    values: Object.entries(properties).map(([name, value]) =>
                        moddle.create('flowable:Property', { name, value })
                    )
                })
            ]
        });

        // 更新元素属性
        modeling.updateProperties(element, { extensionElements });
    }

    // 获取Flowable扩展属性
    function getFlowableProperties(element) {
        const bo = element.businessObject;
        if (!bo.extensionElements) return {};

        const flowableProps = bo.extensionElements.values.find(
            v => v.$type === 'flowable:Properties'
        );

        if (!flowableProps) return {};

        return flowableProps.values.reduce((acc, prop) => {
            acc[prop.name] = prop.value;
            return acc;
        }, {});
    }

    return {
        modeler,
        activeElement,
        activeElementType,
        activeElementBusinessObject,
        setModeler,
        setActiveElement,
        updateElementProperties,
        createFlowableExtension,
        getFlowableProperties
    };
});